package com.xckj.cycling.viewmodel

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import androidx.core.app.ActivityCompat
import androidx.core.location.LocationManagerCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.xckj.cycling.context.AppContext

class MapViewModel : ViewModel() {

    private val locationManager =
        AppContext.globalContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager

    fun isLocationEnabled() = LocationManagerCompat.isLocationEnabled(locationManager)
    private val listener: LocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            locationLiveData.value = location
        }

    }
    val locationLiveData: MutableLiveData<Location> = MutableLiveData()

    fun init() {
        if (ActivityCompat.checkSelfPermission(
                AppContext.globalContext(),
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
                AppContext.globalContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, listener)
        }
    }

    override fun onCleared() {
        super.onCleared()
        locationManager.removeUpdates(listener)
    }
}